using System;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Services;

namespace UniversalAdmin.Api.Services
{
    /// <summary>
    /// 当前用户服务实现
    /// </summary>
    public class CurrentUserService : ICurrentUserService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILogger<CurrentUserService> _logger;

        public CurrentUserService(IHttpContextAccessor httpContextAccessor, ILogger<CurrentUserService> logger)
        {
            _httpContextAccessor = httpContextAccessor;
            _logger = logger;
        }

        public Guid GetCurrentUserId()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext == null)
                {
                    _logger.LogError("CurrentUserService: HttpContext为空");
                    return Guid.Empty;
                }

                var user = httpContext.User;
                if (user == null)
                {
                    _logger.LogError("CurrentUserService: User为空");
                    return Guid.Empty;
                }

                // 查找NameIdentifier声明
                var nameIdentifierClaim = user.FindFirst(ClaimTypes.NameIdentifier);
                if (nameIdentifierClaim != null)
                {
                    _logger.LogInformation($"CurrentUserService: 找到NameIdentifier声明: {nameIdentifierClaim.Value}");
                    return Guid.Parse(nameIdentifierClaim.Value);
                }

                // 查找sub声明（JWT标准）
                var subClaim = user.FindFirst("sub");
                if (subClaim != null)
                {
                    _logger.LogInformation($"CurrentUserService: 找到sub声明: {subClaim.Value}");
                    return Guid.Parse(subClaim.Value);
                }

                // 调试：打印所有声明
                _logger.LogWarning("CurrentUserService: 未找到用户ID声明，当前声明列表:");
                foreach (var claim in user.Claims)
                {
                    _logger.LogWarning($"声明: {claim.Type} = {claim.Value}");
                }

                return Guid.Empty;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "CurrentUserService: 获取用户ID时发生异常");
                return Guid.Empty;
            }
        }
    }
}